package com.jxb.myshop.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
    // 创建一个德鲁伊连接池
    private static DruidDataSource ds;

    static {
        Properties pro = new Properties();
        try {
            pro.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection con = THREAD_LOCAL.get();
        if (con == null) {
            try {
                // 通过连接池创建新的连接
                con = ds.getConnection();
                // 把连接放入
                THREAD_LOCAL.set(con);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return con;
    }

    /**
     * 获取数据源的方法
     * @return
     */
    public static DruidDataSource getDs(){
        return ds;
    }

    // 开启事务
    public static void begin(){
        Connection con = getConnection();
        try {
            con.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 提交事务
    public static void commit(){
        Connection con = getConnection();
        try {
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                con.close();
                // 如果结束事务要清空thread_local
                THREAD_LOCAL.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 事务回滚
    public static void rollback(){
        Connection con = getConnection();
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                con.close();
                // 如果结束事务要清空thread_local
                THREAD_LOCAL.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void closeConnection(Connection con){
        try {
            if (con != null){
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
